﻿using System; 
using System.Linq;
using System.Collections.Generic;
using T.ServiceComponent.DAC.Service;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Base.Dao;
using T.FAS.Runtime.Metadata.Entity.DataModel;

namespace T.FAS.Runtime.DataModel.Dao
{
    public class DataColumnELBDao : DaoService<DataColumn>
    {
        public override string TableName => "fas_dataobjectcolumn";
        public override string IDColumnName => "ID";
        public string ForeignColumn => "DataObjectID";

        public override List<string> ExceptColumnName { get; } = new List<string> { "DefaultValueType", };

        public DataColumnELBDao() : base() { DBName = "TFAS"; }

        /// <summary>
        /// 获取元数据内容
        /// </summary>
        /// <param name="metaDataId"></param>
        /// <returns></returns>
        public List<DataColumn> GetDataColumns(string doId)
        {
            var result = new List<DataColumn>();
            if (string.IsNullOrEmpty(doId))
            {
                return result;
            }
            var dt = base.GetByFilter($"{ForeignColumn}='{doId}'");
            result = DaoUtil.ConvertToEntity<DataColumn>(dt, this.ExceptColumnName);
            return result;
        }

        /// <summary>
        /// 获取元数据内容
        /// </summary>
        /// <param name="metaDataId"></param>
        /// <returns></returns>
        public DataColumn GetDataColumn(string colId)
        {
            var result = new DataColumn();
            if (string.IsNullOrEmpty(colId))
            {
                return result;
            }
            var dt = base.GetByFilter($"{IDColumnName}='{colId}'");
            result = DaoUtil.ConvertToEntity<DataColumn>(dt, this.ExceptColumnName).FirstOrDefault();
            return result;
        }

        /// <summary>
        /// 添加DataColumn
        /// </summary>
        /// <param name="columns"></param>
        public void CreateDataColumn(List<DataColumn> columns)
        {
            try
            {
                //Precision是MySQL中关键词，所以采用自己生成的SQL
                DaoUtil.ExecuteInsertSQL(columns, this);    //创建DataColumn
            }
            catch (Exception e)
            {
                throw new FasException(DataModelErrorCode.DO.CreateColumnError, e.Message, e);
            }
        }

        /// <summary>
        /// 删除DataColumn
        /// </summary>
        /// <param name="DataColumns"></param>
        public void DeleteDataColumn(string doId)
        {
            try
            {
                base.DB.ExecSqlStatement(string.Format(DaoUtil.DeleteSQLWithNoParam, this.TableName, this.ForeignColumn, doId));
            }
            catch (Exception e)
            {
                throw new FasException(DataModelErrorCode.DO.DeleteColumnError, e.Message, e);
            }
        }
    }
}